﻿using Network;
using GameProtocols;
using System.Collections.Generic;
using TrueSync;
using Framework.AssetsManager;
using UnityEngine;

public class LockstepEngine:Singleton<LockstepEngine>
{
    Queue<PKG_FRAME> mFrames;
    public static FP FrameDeltaTime = Time.fixedDeltaTime;

    public int mNextFrameNo
    {
        private set; get;
    }

    public void Reset()
    {
        //缓存镇清空
        mFrames = new Queue<PKG_FRAME>();
        
        //注册消息
        NetManager.Instance.RegistMsg((ushort)ProtoId.MSG_FRAME, onRecvFrame);
        NetManager.Instance.RegistMsg((ushort)ProtoId.MSG_SYN_STATE_NTF, onSyncState);
        //注册循环
        Mainloop.Instance.onFixedUpdate += FixedUpdate;

        mNextFrameNo = 0;
    }
	
    public void Destroy()
    {
        Mainloop.Instance.onFixedUpdate -= FixedUpdate;

        NetManager.Instance.UnregistMsg((ushort)ProtoId.MSG_FRAME, onRecvFrame);
        NetManager.Instance.UnregistMsg((ushort)ProtoId.MSG_SYN_STATE_NTF, onSyncState);
    }

    void FixedUpdate()
    {
        if (mFrames.Count > 0)
        {
            PKG_FRAME frame = mFrames.Dequeue();
            if (frame.frameNo != mNextFrameNo)
            {
                Debug.LogError(string.Format("FrameNo Mismatch, recv: {0}, next: {1}", frame.frameNo, mNextFrameNo));
            }
            else
            {
                GameManager.Instance.Tick(frame);
                mNextFrameNo++;
            }
        }
    }

    void onRecvFrame(object msg)
    {
        PKG_FRAME frame = (PKG_FRAME)msg;
        mFrames.Enqueue(frame);
    }

    void onSyncState(object msg)
    {
        PKG_SYN_STATE_NTF syncState = (PKG_SYN_STATE_NTF)msg;
        var oldFrames = syncState.frames;
        foreach (var aframe in oldFrames)
            mFrames.Enqueue(aframe);
    }
}
